<?php

namespace App\Http\Controllers\College\Web;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Library\Rms\RmsShopApi;
use App\Models\College\CollegeTrainingOrderLogModel;
use App\Models\College\CollegeTrainingOrderModel;
use App\Service\College\CollegeTrainingOrderService;
use App\Service\College\CollegeTrainOrderService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TrainingOrderController extends BaseController
{
    /**
     * 培训订单列表
     * @param Request $request
     * @throws GuzzleException
     */
    public function list(Request $request)
    {
        $pageSize  = $request->get('pageSize', 10);
        $pageNum   = $request->get('pageNum', 1);        //Web参数
        $orderNo   = $request->get('orderNo', '');
        $planName  = $request->get('planName', '');
        $shopIds   = $request->get('shopIds', '');
        $trainType = $request->get('trainType', 0);
        $startTime = $request->get('startTime', '');
        $endTime   = $request->get('endTime', '');
        $status    = $request->get('status', 0);
        $export    = (bool)$request->get('export', 0);
        $teacherShopIds = (string)$request->get('teacherShopId', '');
        $campus = (int)$request->get('campus');
        $startOpenTime = $request->get('startOpenTime', '');
        $endOpenTime = $request->get('endOpenTime', '');

        if ($export) {
            $pageNum  = 1;
            $pageSize = 9999;
        }

        return $this->success(CollegeTrainOrderService::getTrainOrderList($pageSize, $pageNum, $orderNo, $planName, $shopIds, $trainType, $startTime, $endTime, $status, 0, $teacherShopIds, $export, $campus, $startOpenTime, $endOpenTime));
    }

    /**
     * @throws GuzzleException
     */
    public function detail(Request $request, $id): JsonResponse
    {
        return $this->success(CollegeTrainOrderService::getTrainOrderDetail($id, FeishuWebAuth::$userId));
    }

    /**
     * 更新预计参训人员
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function update(Request $request, $id): JsonResponse
    {
        return $this->success();
    }

    /**
     * 通过shopId获得staff列表
     * @param Request $request
     * @param int $shopId
     * @return JsonResponse
     * @throws GuzzleException
     */
    public function getShopStaff(Request $request, int $shopId): JsonResponse
    {
        $staffData = (new RmsShopApi())->getShopStaffListByShopId($shopId)['data']['list'] ?? [];
        $userList  = collect($staffData)->map(function ($staff) {
            return [
                'position' => collect($staff['role'])->implode('roleName', ','),
                'name'     => $staff['username'],
                'mobile'   => $staff['mobile'],
                'userId'   => $staff['id'],
            ];
        })->toArray();
        return $this->success($userList);
    }

    /**
     * 关闭培训订单
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function close(Request $request, $id)
    {
        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($id))->close($currentUid);

        return $this->success();
    }

    /**
     * 商学院确认
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function confirm(Request $request, int $id): JsonResponse
    {
        $userId = getRmsUserId();
        $this->validate($request, [
            'campus'        => 'required|integer',
            'planId'        => 'required|integer',
            'teacherShopId' => 'required|integer',
            'userIds'       => 'array',
        ]);

        (new CollegeTrainingOrderService($id))->confirm($userId, $request->campus, $request->planId, $request->teacherShopId, (array)$request->userIds);

        return $this->success();
    }

    /**
     * 上传实操信息
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function upload(Request $request, int $id): JsonResponse
    {
        $this->validate($request, [
            'practiceTrainingUrls'      => 'required|array',
            'failLetterUrls'            => 'array',
            'users.*.userId'            => 'required|integer',
            'users.*.practiceCheckUrls' => 'required|array',
            'users.*.practiceScore'     => 'required|integer',
            'users.*.comment'           => 'required|string|min:1|max:500',
            'portrait'                  => 'required|string|min:1|max:500',
        ]);

        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($id))->upload(
            $request->practiceTrainingUrls,
            $request->failLetterUrls,
            $request->users,
            $currentUid,
            $request->portrait
        );

        return $this->success();
    }

    /**
     * 新增参训人员
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function userAdd(Request $request, int $id): JsonResponse
    {
        $this->validate($request, [
            'userId' => 'required|integer',
        ]);

        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($id))->userAdd($request->userId, $currentUid);

        return $this->success();
    }

    /**
     * 移除参训人员
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function userRemove(Request $request, int $id): JsonResponse
    {
        $this->validate($request, [
            'userId' => 'required|integer',
        ]);

        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($id))->userRemove($request->userId, $currentUid);

        return $this->success();
    }

    /**
     * 手动新增门店培训单
     * @param Request $request
     * @return JsonResponse
     */
    public function orderAdd(Request $request): JsonResponse
    {
        $shopId = $request->post('shopId');

        $this->validate($request, [
            'shopId' => 'required|integer',
        ]);

        $currentUid = getRmsUserId();

        $id = (new CollegeTrainingOrderService(0))->orderAdd($currentUid, $shopId, true);

        return $this->success(['id' => $id]);
    }

    /**
     * 补考
     * @param Request $request
     * @return JsonResponse
     */
    public function orderRepair(Request $request): JsonResponse
    {
        $examNo          = $request->post('examNo');
        $trainingOrderId = $request->post('trainingOrderId');

        $this->validate($request, [
            'examNo'          => 'required|string',
            'trainingOrderId' => 'required|integer',
        ]);

        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($trainingOrderId))->orderRepair($examNo, $currentUid);

        return $this->success();
    }

    /**
     * 修改带训门店
     * @param Request $request
     * @return JsonResponse
     */
    public function editTeacherShop(Request $request, int $id): JsonResponse
    {
        $teacherShopId = (int)$request->get('teacherShopId');

        $this->validate($request, [
            'teacherShopId' => 'required|integer',
        ]);

        $currentUid = getRmsUserId();

        (new CollegeTrainingOrderService($id))->editTeacherShop($teacherShopId, $currentUid);

        return $this->success();
    }
}
